package cz.ctu.guiproject.client.resources.utils;

import java.io.FileNotFoundException;

import android.util.Log;
import static cz.ctu.guiproject.client.resources.constants.Constants.*;
import static cz.ctu.guiproject.client.resources.constants.Logger.*;
import cz.ctu.guiproject.client.xml.XmlDecodeFactory;
import cz.ctu.guiproject.client.xml.XmlEncodeFactory;

public class ConfigProvider {

	private String[] config;

	private static ConfigProvider instance;

	private ConfigProvider() {
		this.config = loadConfig();
	};

	public static ConfigProvider getInstance() {
		if (instance == null) {
			instance = new ConfigProvider();
		}
		return instance;
	}

	public String[] getConfig() {
		return config;
	}

	public void setConfig(String[] config) {
		this.config = config;
		saveConfig();
	}

	private String[] loadConfig() {
		String[] config;
		// TODO odstrani "zbytecny" try-catch
		try {
			final String configXml = FileHandler.loadTextFile(CONFIG_FILE);
			config = (configXml == null) ? new String[] { "", "" } : XmlDecodeFactory.decodeConfig(configXml);
		} catch (FileNotFoundException e) {
			Log.e(TAG, "Error opening config file, maybe it does not exist... " + e.getMessage());
			config = null;
		}
		return config;
	}

	private void saveConfig() {
		final String ip = config[0];
		final int port = Integer.parseInt(config[1]);
		final String data = XmlEncodeFactory.encodeConfig(ip, port);
		FileHandler.saveTextFile(CONFIG_FILE, data);
	}
}
